const _ = require("lodash");
const Utils = require("../utils");
const { IS_OK,SERVER_ERROR_CODE,NO_RESULT,PARAM_ERROR} = require("../config/admin/state_code");
const Service = require("egg").Service;
class UserServer extends Service{
  async register(data){
    try{
      let { ctx } = this;
      let { username , password , order } = data;
      let findRs = await this.app.mysql.select("user",{
        where:{name:username},
        columns:['id']
      });

      if( findRs.length === 0 ){
        let encryptPassword  = await  Utils.hash_encrypt(password);
        let rs = await this.app.mysql.insert("user",{
          name: username,
          password: encryptPassword,
          order: order,
          is_super: await this._isFirstUser() ? 1 : 0,
          state: 0
        });
        return Utils.createServerMsg("创建成功!",IS_OK,"")
      }

      if(findRs.length > 0){
        return Utils.createServerMsg("该账户已存在!",NO_RESULT,"")
      }

    }catch (e) {
      return Utils.createServerMsg("注册失败!",SERVER_ERROR_CODE,e);
    }
  }

  async login (data){
    let { ctx } = this;
    let { username , password  } = data;
    let findRs = await this.app.mysql.select("user",{
      where:{name:username,state:0},
      columns:['id',"password","name","order","is_super"]
    });
    if(findRs.length === 0) return Utils.createServerMsg("用户不存在",NO_RESULT,"");

    if(findRs.length > 0){
      let { password:vaildPassword,name,order,is_super,id } = findRs[0];
      let passwordIsSame = await Utils.hash_compare(password,vaildPassword);
      if( passwordIsSame ){
         return Utils.createServerMsg("登录成功",IS_OK,{
           name,
           order,
           is_super,
           id
         })
      }else{
         return Utils.createServerMsg("登录失败,密码错误",NO_RESULT,"")
      }
    }
  }

  async userTotal(){
    const mysql = this.app.mysql;
    let Rs = await mysql.query("select COUNT(id) as total  from user where state = 0");
    if(Rs.length >= 1){
      return Rs[0].total
    }else{
      return 0
    }
  }

  /***
   *  @index 获得普通用户
   *  @param page <number> page 分页
   *  @param size <number> 页面尺寸
   *  @param filter <object> 过滤条件
   * **/
  async getNormalUsers (page,size,filter){
    const mysql = this.app.mysql;
    try{
      let findRs = await mysql.select("user",{
        where: Object.assign({ is_super:0, state : 0},filter) ,
        limit: size,
        offset: page >= 1 ? (page - 1) * size : 0,
        columns:['id','name','order']
      });
      if(findRs.length > 0) {
        let total = await this.userTotal() - 1;
        return Utils.createServerMsg("获得成功",IS_OK,{
          list:findRs,
          page,
          total
        })
      }else{
        return Utils.createServerMsg("无此用户",NO_RESULT,"")
      }
    }catch (e) {
        return Utils.createServerMsg("参数错误",SERVER_ERROR_CODE,{
          error:e
        })
    }
  }

  /***
   *  @index 刪除用戶
   *  @param id <number> 用戶id
   * **/
  async delUser (id){
    const mysql = this.app.mysql;
    try{
      const Rs = await mysql.update('user',{state:1},{where:{id}});
      if(Rs.affectedRows >= 1){
        return Utils.createServerMsg("刪除成功",IS_OK,{Rs});
      }else{
        return Utils.createServerMsg("删除失败",PARAM_ERROR,{Rs});
      }
    }catch (e) {
      return Utils.createServerMsg("参数错误",SERVER_ERROR_CODE,{
        error:e,
        id
      })
    }
  }

  /***
   *  @index 修改用户密码
   *  @param id <number> 用戶id
   *  @param password <string> 用户密码
   * **/
  async editUserPassWord (id,password){
    const mysql = this.app.mysql;
    try{
      const Rs = await mysql.update('user',{password: await Utils.hash_encrypt(password) },{where:{id}});
      if(Rs.affectedRows >= 1){
        return Utils.createServerMsg("修改密码成功",IS_OK,{Rs});
      }else{
        return Utils.createServerMsg("修改密码失败",PARAM_ERROR,{Rs});
      }
    }catch (e) {
      return Utils.createServerMsg("参数错误",SERVER_ERROR_CODE,{
        error:e,
        id,
      })
    }
  }

  //判断是否为第一位 第一位 为超级管理员 具有删除用户的权限
  async _isFirstUser(){
    let findRs = await this.app.mysql.select("user",{
      columns:['id'],
      limit:1
    });
    return findRs.length === 0;
  }


}
module.exports =UserServer;


